package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;


@Aspect
@Slf4j
@Component
public class AutoFillAspect {

    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段自动填充");
        // 获取当前被拦截的方法上的注解
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();//方法签名对象
        // 获取注解对象
        AutoFill autoFill = signature.getMethod().getDeclaredAnnotation(AutoFill.class);
        // 获取注解对象中定义的操作类型
        OperationType operationType = autoFill.value();
        // 获取当前被拦截的方法的参数列表
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object arg = args[0];
        if (OperationType.INSERT.equals(operationType)){
            try {
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class)
                        .invoke(arg,LocalDateTime.now());
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class)
                        .invoke(arg,LocalDateTime.now());
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class)
                        .invoke(arg, BaseContext.getCurrentId());
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class)
                        .invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (OperationType.UPDATE.equals(operationType)){
            try {
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class)
                        .invoke(arg,LocalDateTime.now());
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class)
                        .invoke(arg, BaseContext.getCurrentId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
